<template>
  <div class="consumer-page activity-list-page">
    <el-breadcrumb class="breadcrumb page-title" separator="/">
      <el-breadcrumb-item>Category translation</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container-padding">
      <!--serchBox-->
      <div class="search-box">
        <el-form :inline="true" label-position="top" :model="searchForm" size="mini" ref="ruleForm"
                 class="demo-ruleForm main-search-box">
          <el-row>
            <!--Status-->
            <el-form-item label="Status" style="width: 200px;margin-right: 10px">
              <el-select style="width: 200px" v-model="searchForm.status" placeholder="">
                <el-option v-for="i in statusOption" :key="i.value" :label="i.label" :value="i.value"></el-option>
              </el-select>
            </el-form-item>
            <!--English-->
            <el-form-item label="English" style="width: 200px;">
              <el-input v-model="searchForm.categoryName" placeholder=""></el-input>
            </el-form-item>
            <!--search-->
            <el-form-item style="margin-top: 37px;margin-left: 30px;">
              <el-button @click="getList" type="primary" style="width:80px">Search</el-button>
            </el-form-item>
            <!--new-->
            <el-form-item style="margin-top: 37px">
              <el-button @click="categoryEdit(null)" type="success" style="width:80px">New
              </el-button>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <!--list-->
      <div class="list-items-box">
        <el-table
          :data="tableData"
          v-loading="tableLoading"
          border
          ref="singleTable"
          highlight-current-row
          @current-change="handleCurrentChange"
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <!--edit-->
          <el-table-column
            prop="" label="Edit"
            align="center"
            width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="categoryEdit(scope)">Edit</el-button>
            </template>
          </el-table-column>
          <!--ID-->
          <el-table-column
            prop="id"
            label="ID"
            align="center"
            min-width="80">
          </el-table-column>
          <!--category1-->
          <el-table-column
            prop="category1_name"
            label="Category1"
            align="center"
            min-width="140">
          </el-table-column>
          <!--category2-->
          <el-table-column
            prop="category2_name"
            label="Category2"
            align="center"
            min-width="150">
          </el-table-column>
          <!--english-->
          <el-table-column
            prop="categoryName"
            label="English"
            align="center"
            min-width="120">
          </el-table-column>
          <!--zawgyi-->
          <el-table-column
            prop="zawgyi"
            label="Zawgyi"
            align="center"
            min-width="150">
          </el-table-column>
          <!--Created Date-->
          <el-table-column
            prop="createDatetime"
            label="Created Date"
            align="center"
            min-width="160">
            <template slot-scope="scope">
              <p>{{dateFormat(scope.row.createDatetime,)}}</p>
            </template>
          </el-table-column>
          <!--Created By-->
          <el-table-column
            prop="createBy"
            label="Created By"
            align="center"
            min-width="240">
          </el-table-column>
          <!--Updated Date-->
          <el-table-column
            prop="updateDatetime"
            label="Updated Date"
            align="center"
            min-width="160">
            <template slot-scope="scope">
              <p>{{dateFormat(scope.row.updateDatetime,)}}</p>
            </template>
          </el-table-column>
          <!--Updated By-->
          <el-table-column
            prop="updateBy"
            label="Updated By"
            align="center"
            min-width="240">
          </el-table-column>
        </el-table>
        <!--分页-->
        <div class="block" style="margin-top: 15px;text-align: center;">
          <el-pagination
            @size-change="handleChangeSize"
            @current-change="handleChangePage"
            :current-page="pageData.pageNum"
            :page-size="pageData.pageSize"
            :page-sizes="[10, 20, 50, 100, 500]"
            :page-count="pageInfo.totalPages"
            :total="pageInfo.totalCount"
            layout="total, prev, pager, next, jumper, sizes">
          </el-pagination>
        </div>
      </div>
      <!--dialog-->
      <el-dialog
        title="Category Edit"
        :visible.sync="dialogVisible"
        width="630px"
      >
        <div class="consumer-page activity-list-page">
          <div class="container-padding" v-loading.fullscreen.lock="fullscreenLoading">
            <!--serchBox-->
            <div class="search-box">
              <el-form :inline="true" label-position="top" :model="editForm" size="mini" ref="form" :rules="rules"
                       class="demo-ruleForm main-search-box">
                <el-row>
                  <!--Status-->
                  <el-form-item label="Status" style="width: 200px;margin-right: 10px">
                    <el-select style="width: 200px" v-model="editForm.status" placeholder="">
                      <el-option v-for="i in editStatusOption" :key="i.value" :label="i.label"
                                 :value="i.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-row>
                <el-row>
                  <!--第一级菜单-->
                  <el-form-item label="Category1" style="width: 200px;margin-right: 10px" prop="firstCategory">
                    <el-select style="width: 200px" v-model="editForm.firstCategory" @change="getSecondaryData">
                      <el-option v-for="i in categoryData" :key="i.id" :label="i.name" :value="i.name"></el-option>
                    </el-select>
                  </el-form-item>
                  <!--第二级菜单-->
                  <el-form-item label="Category2" style="width: 200px;margin-right: 10px" prop="secondaryCategory"
                                v-if="secondaryData.length>0"
                  >
                    <el-select style="width: 200px" v-model="editForm.secondaryCategory" @change="getThirdData"
                    >
                      <el-option v-for="i in secondaryData" :key="i.id" :label="i.name" :value="i.name"></el-option>
                    </el-select>
                  </el-form-item>
                </el-row>
                <el-row>
                  <!--english-->
                  <el-row>
                    <el-col class="english-require">
                      <el-form-item
                        label="English"
                        style="width: 250px;margin-left:4px;"
                        prop="categoryName"
                      >
                        <el-input
                          v-model="editForm.categoryName"
                          class="name-label"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-row>
                <el-row>
                  <!--zawgyi-->
                  <el-row>
                    <el-col>
                      <el-form-item
                        label="Zawgyi ( MaxLength : 200 )"
                        style="width: 350px;margin-left:8px;"
                      >
                        <el-input
                          v-model="editForm.zawgyi"
                          class="name-label"
                          maxlength="200"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-row>
                <!--search-->
                <el-button @click="dialogVisible=false" type="info" style="width:80px">Cancel</el-button>
                <!--new-->
                <el-button @click="onSubmit" type="success" style="width:80px">Save</el-button>
              </el-form>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {getCategoryTransition, categoryTransitionEdit, categoryTransitionNew} from '../../api/guc_api.js'
  import categoryData from '@/json/category.json';
  import qs from 'qs';

  export default {
    name: 'shopUser',
    data() {
      return {
        searchForm: {
          status: '',
          categoryName: '',
        },
        statusOption: [
          {
            label: '',
            value: ''
          },
          {
            label: 'Active',
            value: '1'
          },
          {
            label: 'Deleted',
            value: '0'
          },
        ],
        pageData: {
          pageNum: 1,
          pageSize: 10,
        },
        pageInfo: {
          totalCount: 0,
          totalPages: 0
        },
        tableLoading: false,
        tableData: [],
        // 当前行
        currentRow: null,
        dialogVisible: false,
        editStatusOption: [
          {
            label: 'Active',
            value: '1'
          },
          {
            label: 'Deleted',
            value: '0'
          }
        ],
        editForm: {
          categoryId: '',
          category1_id: '',
          category2_id: '',
          status: '1',
          categoryName: '',
          zawgyi: '',
          firstCategory: '',
          secondaryCategory: '',
        },
        categoryName: '',
        //本地数据
        categoryData,
        secondaryData: [],
        fullscreenLoading: false,
        rules: {
          categoryName: [
            {
              validator: (rule, value, callback) => {
                if (value === "") {
                  callback(new Error("can not be empty"));
                }
                else {
                  callback();
                }
              },
              trigger: "change"
            }
          ]
        },
      }
    },
    methods: {
      //新增编辑
      categoryEdit(scope) {
        this.dialogVisible = true;
        this.clearEditForm()
        //编辑
        if (scope) {
          // 从该行获取数据初始化编辑表单
          let data = scope.row
          this.editForm.status = data.status + '';
          this.editForm.categoryName = data.categoryName;
          this.editForm.zawgyi = data.zawgyi
          this.editForm.firstCategory = data.category1_name
          this.editForm.secondaryCategory = data.category2_name
          this.editForm.categoryId = data.id
          this.editForm.category1_id = data.category1_id
          this.editForm.category2_id = data.category2_id
          //对category初始化
          this.categoryData.forEach((item, index) => {
            if (item.id === this.editForm.category1_id) {
              this.secondaryData = this.categoryData[index].children || [];
            }
          })
        }
      },
      // 获取二级菜单
      getSecondaryData() {
        //根据一级菜单的name找到它对应的id
        if (this.editForm.firstCategory) {
          this.categoryData.forEach((item) => {
            if (item.name === this.editForm.firstCategory) {
              this.editForm.category1_id = item.id
              //重置二级数据
              this.editForm.category2_id = ''
              this.editForm.secondaryCategory = ''
            }
          })
        }
        this.categoryData.forEach((item, index) => {
          if (item.id === this.editForm.category1_id) {
            this.secondaryData = this.categoryData[index].children || [];
          }
        })

      },
      // 获取三级菜单
      getThirdData() {
        if (this.editForm.secondaryCategory) {
          this.secondaryData.forEach((item) => {
            if (item.name === this.editForm.secondaryCategory) {
              this.editForm.category2_id = item.id
            }
          })
        }
      },
      //提交表单
      onSubmit() {
        if (!this.editForm.categoryName) {
          this.messageToastErr('Please fill required area')
        }
        else {
          let params = {
            categoryId: this.editForm.categoryId,
            category1_id: this.editForm.category1_id,
            category2_id: this.editForm.category2_id,
            status: this.editForm.status,
            categoryName: this.$translateLang(this.editForm.categoryName || '', 'zawgyiTounicode') || '',
            zawgyi: this.$translateLang(this.editForm.zawgyi || '', 'zawgyiTounicode') || '',
          }
          params = qs.stringify(params);
          let config = {
            "Content-Type": "multipart/form-data"
          };
          this.fullscreenLoading = true;
          //编辑
          if (this.editForm.categoryId) {
            categoryTransitionEdit(params, config)
              .then(res => {
                this.fullscreenLoading = false;
                this.clearEditForm()
                if (res.data.errorID == 0) {
                  this.dialogVisible = false
                  this.messageToastSuccess('Edit success!')
                  //重新获取表格数据
                  this.getList()
                }
                else {
                  this.messageToastErr(res.data.message)
                }
              })
              .catch(err => {
                this.fullscreenLoading = false;
                this.dialogVisible = false
                this.clearEditForm()
                console.log(err)
              })
          }
          // 新增
          else {
            categoryTransitionNew(params, config)
              .then(res => {
                this.fullscreenLoading = false;
                this.clearEditForm()
                if (res.data.errorID == 0) {
                  this.dialogVisible = false
                  this.messageToastSuccess('New add success!')
                  //重新获取表格数据
                  this.getList()
                }
                else {
                  this.messageToastErr(res.data.message)
                }
              })
              .catch(err => {
                this.fullscreenLoading = false;
                this.dialogVisible = false
                this.clearEditForm()
                console.log(err)
              })
          }

        }
      },
      clearEditForm() {
        //关闭dialog之前都要对数据进行清空
        this.editForm.categoryId = ''
        this.editForm.category1_id = ''
        this.editForm.category2_id = ''
        this.editForm.status = '1'
        this.editForm.categoryName = ''
        this.editForm.zawgyi = ''
        this.editForm.firstCategory = ''
        this.editForm.secondaryCategory = ''
      },
      // 用来控制表格行点击选中状态
      handleCurrentChange(val) {
        this.currentRow = val;
      },
      //用来控制单双行样式
      tableRowClassName({row, rowIndex}) {
        if (rowIndex % 2 === 1) {
          return 'odd-row';
        }
        else if (rowIndex % 2 === 0) {
          return 'even-row';
        }
        return '';
      },
      handleChangeSize(val) {
        this.pageData.pageSize = parseInt(val)
        this.pageData.pageNum = 1
        this.getList()
      },
      handleChangePage(val) {
        this.pageData.pageNum = val
        this.getList()
      },
      //日期格式化
      dateFormat(value) {
        if (!value) {
          return ''
        }
        else {
          let date = new Date(value)
          let Y = date.getFullYear()
          let m = date.getMonth() + 1
          let d = date.getDate()
          let H = date.getHours()
          let i = date.getMinutes()
          let s = date.getSeconds()
          if (m < 10) {
            m = '0' + m
          }
          if (d < 10) {
            d = '0' + d
          }
          if (H < 10) {
            H = '0' + H
          }
          if (i < 10) {
            i = '0' + i
          }
          if (s < 10) {
            s = '0' + s
          }
          let t = Y + '-' + m + '-' + d + '  ' + H + ':' + i + ':' + s
          return t
        }
      },
      //对表格中的内容进行unicode转交集
      unicodeTozawgyi(value) {
        if (value) {
          return this.$translateLang(value, 'unicodeTozawgyi') || ''
        } else {
          return value;
        }
      },
      // message alert 用于前端错误提示信息
      messageToastErr(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: 'error'
        })
      },
      //提交成功显示的消息
      messageToastSuccess(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: "success"
        });
      },
      getList(pageNum) {
        this.tableLoading = true;
        if (pageNum == 1) {
          this.pageData.pageNum = 1;
        }
        if (this.searchForm.name) {
          this.searchForm.name = this.$translateLang(this.searchForm.name || '', 'zawgyiTounicode') || ''
        }
        getCategoryTransition(Object.assign(this.searchForm, this.pageData)).then((res) => {
          this.tableData = res.data.object.list || []
          // 分页信息配置
          this.pageInfo.totalPages = res.data.object.pages
          this.pageInfo.totalCount = res.data.object.total
          this.tableLoading = false;
        }).catch((e) => {
          this.tableLoading = false;
        })
      },
    },
    mounted() {
      this.getList(1)
    }
  }
</script>
<style>
  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px !important;
  }

  .breadcrumb {
    margin-bottom: 20px;
  }

  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px;
  }

  .search-box {
    position: relative;
    border-bottom: 1px solid #eee;
  }

  .more-box, .list-items-box {
    padding-top: 20px;
    padding-bottom: 10px;
  }

  .list-items-box .el-form--inline.el-form--label-top .el-form-item__content {
    display: inline-block;
  }

  .container-padding {
    padding: 0 40px;
  }

  .new-user-dialog .el-form-item {
    margin-bottom: 0 !important;
  }

  .activity-list-page .el-checkbox + .el-checkbox {
    margin-left: 0 !important;
    margin-right: 30px !important;
  }

  .english-require::before {
    content: "*";
    color: #f56c6c;
    left: -2px;
    position: relative;
    top: 5px;
  }
</style>
